<template>
  <view class="record">

    <view class="record-map">
      <map v-if="!modalVisible" :style="'width:100%;height:' + mapHeight + 'px'" id="map" :markers="mapInfo.markers||[]"
           :longitude="mapInfo.longitude"
           :latitude="mapInfo.latitude" :scale="mapInfo.scale" :polyline="polylineList||[]">
        <cover-view class="record-status" v-if="recordStatus">
          <cover-view class="record-status-icon"></cover-view>
          <cover-view class="record-status-text">录制中
          </cover-view>
        </cover-view>

        <cover-view class="record-btn" v-if="isVisible">
          <cover-view class="record-btn-main" @click="onChangeRecord">
            {{ recordStatus ? '结束录制' : '开始录制' }}
          </cover-view>
        </cover-view>
      </map>
      <!--      <customMap :height="`${mapHeight}px`" :mapInfo="mapInfo"></customMap>-->
    </view>


    <!--  保存录制  -->
    <Modal v-if="modalVisible" :visible="modalVisible" title="路径命名" @close="onCloseModal"
           @confirm="onConfirmModal">

      <view class="file-input">
        <input placeholder-class="file-input-placeholder" type="text" v-model="fileName" placeholder="请输入路径名称">
      </view>

    </Modal>
  </view>
</template>

<script setup>
import {onLoad, onUnload} from "@dcloudio/uni-app";
import {ref,} from 'vue'
import {useRecord} from "./record"

const {
  mapHeight,
  points,
  centerLongitude,
  centerLatitude,
  recordStatus,
  fileName,
  modalVisible,
  onChangeRecordStatus,
  onCloseModal,
  onConfirmModal
} = useRecord()

const isVisible = ref(true)

const mapInfo = ref({
  longitude: centerLongitude,//取轨迹中间点
  latitude: centerLatitude,//取轨迹中间点
  scale: 16,
})

onLoad(() => {
  isVisible.value = true
  const systemInfo = uni.getSystemInfoSync()
  mapHeight.value = systemInfo.windowHeight - 88
})

const onChangeRecord = () => {
  resetRecord()
  if (!recordStatus.value) {
    startTrackAnimation()
  }
  onChangeRecordStatus()
}

/***轨迹相关逻辑***/
const intervalId = ref(0);
const currentPoints = ref([]);
const polylineList = ref([{
  points: currentPoints.value,
  color: '#007AFF',
  width: 16,
  arrowLine: false
}]);
const startTrackAnimation = () => {
  let idx = 0;
  intervalId.value = setInterval(() => {
    if (idx >= points.length) {
      clearInterval(intervalId.value);
      return;
    }
    idx++;
    currentPoints.value = points.slice(0, idx);
    polylineList.value = [{
      ...polylineList.value[0],
      points: currentPoints.value
    }];
  }, 300);
}

const resetRecord = () => {
  clearInterval(intervalId.value);
  currentPoints.value = []
  polylineList.value = [...[{
    points: currentPoints.value,
    color: '#007AFF',
    width: 16,
    arrowLine: false
  }]]
}

onUnload(() => {
  resetRecord()
  isVisible.value = false
})

</script>

<style lang="scss" scoped>
@import "record";
</style>
